package com.party.admin.biz.mall;

import com.party.admin.biz.file.FileBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonQuery;
import com.party.admin.web.dto.output.mall.MallShowSubjectTemplateOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.MallShowCategory;
import com.party.core.model.mall.MallShowGoods;
import com.party.core.model.mall.MallShowSubjectTemplate;
import com.party.core.model.mall.MallShowSubjectTemplateQuery;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.mall.IMallShowCategoryService;
import com.party.core.service.mall.IMallShowGoodsService;
import com.party.core.service.mall.IMallShowSubjectTemplateService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 展示商品主题
 * Created by wei.li
 *
 * @date 2017/8/25 0025
 * @time 16:21
 */

@Service
public class MallShowSubjectTemplateBizService {

    private static Logger logger = LoggerFactory.getLogger(MallShowSubjectTemplateBizService.class);

    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;

    @Autowired
    private IMallShowCategoryService mallShowCategoryService;

    @Autowired
    private IMallShowGoodsService mallShowGoodsService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private FileBizService fileBizService;

    public static final String SHOW_SUBJECT_TEMPLATE_FOLDER_NEW = "showSubjectTemplate_new";

    public static final String SHOW_SUBJECT_TEMPLATE_FOLDER = "showSubjectTemplate";

    /**
     * 主题模板列表
     *
     * @param templateQuery
     * @param page          分页参数
     * @return 列表数据
     */
    public List<MallShowSubjectTemplateOutput> list(MallShowSubjectTemplateQuery templateQuery, Page page) {
        if (null != templateQuery.getTimeType() && !new Integer(0).equals(templateQuery.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(templateQuery.getTimeType());
            templateQuery.setCreateStart(commonQuery.getCreateStart());
            templateQuery.setCreateEnd(commonQuery.getCreateEnd());
        }
        List<MallShowSubjectTemplate> r = mallShowSubjectTemplateService.queryPageList(templateQuery, page);
        return LangUtils.transform(r, (mallShowSubjectTemplate) -> {
            String filePath = fileBizService.getUploadCIPath(mallShowSubjectTemplate.getCreateBy(), SHOW_SUBJECT_TEMPLATE_FOLDER_NEW);
            MallShowSubjectTemplateOutput mallShowSubjectTemplateOutput = MallShowSubjectTemplateOutput.transform(mallShowSubjectTemplate);
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + mallShowSubjectTemplate.getId());
            mallShowSubjectTemplateOutput.setQrCode(qrCodeUrl);
            return mallShowSubjectTemplateOutput;
        });
    }

    /**
     * 复制主题模板
     *
     * @param sourceTemplateId 模板id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean copyTemplateBiz(String sourceTemplateId) {
        MemberGroup cur = RealmUtils.getCurrentUser();
        try {
            MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(sourceTemplateId);
            if (null == mallShowSubjectTemplate) {
                throw new Exception("主题分类不存在");
            }
            // 修改主题分类对象
            mallShowSubjectTemplate.setOrgNum(0);
            mallShowSubjectTemplate.setUpdateBy(cur.getId());
            mallShowSubjectTemplate.setCreateBy(cur.getId());
            mallShowSubjectTemplate.setCreateDate(null);
            mallShowSubjectTemplate.setUpdateBy(null);
            mallShowSubjectTemplate.setId(null);
            String newTemplateId = mallShowSubjectTemplateService.insert(mallShowSubjectTemplate);

            // 复制类型
            List<MallShowCategory> mallShowCategories = mallShowCategoryService.findByTemplateId(sourceTemplateId);
            for (MallShowCategory showCategory : mallShowCategories) {
                String sourceCategoryId = showCategory.getId();
                showCategory.setId(null);
                showCategory.setCreateBy(null);
                showCategory.setUpdateBy(null);
                showCategory.setTemplateId(newTemplateId);
                showCategory.setCreateBy(cur.getId());
                showCategory.setUpdateBy(cur.getId());
                // todo 以后添加父子级关系后, 这里需要修改
                String newCategoryId = mallShowCategoryService.insert(showCategory);

                List<MallShowGoods> mallShowGoods = mallShowGoodsService.findByCategoryId(sourceCategoryId);
                for (MallShowGoods showGoods : mallShowGoods) {
                    showGoods.setId(null);
                    showGoods.setUpdateBy(null);
                    showGoods.setCreateBy(null);
                    showGoods.setUpdateBy(cur.getId());
                    showGoods.setCreateBy(cur.getId());
                    showGoods.setCategoryId(newCategoryId);
                    mallShowGoodsService.insert(showGoods);
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("复制主题模板异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 获取模板数据
     *
     * @param id
     * @return
     */
    public AjaxResult getData(String id) {
        AjaxResult ajaxResult = new AjaxResult();
        MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(id);
        if (null == mallShowSubjectTemplate) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("未找到该模板, id = " + id);
            return ajaxResult;
        }
        //处理富文本
        if (StringUtils.isNotEmpty(mallShowSubjectTemplate.getContent())) {
            String content = StringUtils.unescapeHtml4Video2Iframe(mallShowSubjectTemplate.getContent());
            mallShowSubjectTemplate.setContent(content);
        }
        if (StringUtils.isNotEmpty(mallShowSubjectTemplate.getBuyInstruction())) {
            String buyInstruction = StringUtils.unescapeHtml4Video2Iframe(mallShowSubjectTemplate.getBuyInstruction());
            mallShowSubjectTemplate.setBuyInstruction(buyInstruction);
        }
        ajaxResult.setData(mallShowSubjectTemplate);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 删除模板
     *
     * @param templateId 模板id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteTemplateBiz(String templateId) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(templateId)) {
                endResult = false;
                return endResult;
            }
            MallShowSubjectTemplate template = mallShowSubjectTemplateService.get(templateId);
            if (template == null) {
                endResult = false;
                return endResult;
            }
            memberId = template.getCreateBy();
            mallShowCategoryService.deleteByTemplateId(templateId);
            mallShowGoodsService.deleteBySubjectId(templateId);
            mallShowSubjectTemplateService.delete(templateId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除主题分类失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, SHOW_SUBJECT_TEMPLATE_FOLDER_NEW);
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, templateId);
                    cosBizService.deleteFile(detailPath);
                } catch (Exception e) {
                    logger.error("删除主题分类二维码失败", e);
                }
            }
        }
        return endResult;
    }
}
